package com.scau.controller;

import com.scau.dto.CBECReturn;
import com.scau.dto.UserInfo;
import com.scau.handleException.ResultCode;
import com.scau.pojo.SystemUser;
import com.scau.security.Jwt;
import com.scau.service.ISystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

// 告诉spring mvc这是一个控制器类
@Controller
@CrossOrigin
@RequestMapping("")
public class LoginController {

    @Autowired
    ISystemUserService service;

//    @RequestMapping(value="/user/toLoginPage",produces = "application/json;charset=UTF-8;")
//    @ResponseBody
//    public String toSignPage(){
//        return "UserLogin";
//    }


    //判断username、password和数据库是否一致
    @RequestMapping(value = "/user/login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8;")
    @ResponseBody
    public CBECReturn login(@RequestBody SystemUser systemUser) {

        if (null == systemUser) {
            return CBECReturn.build(ResultCode.REQUESTBODY_ERROR);
        }

        SystemUser temp = service.selectUser(systemUser.getUsername());
        if (temp == null) {
            CBECReturn.build(ResultCode.USER_NOT_EXIST);
        } else if (temp.getPassword().equals(systemUser.getPassword())) {
            System.out.println(temp);
            String token = Jwt.sign(systemUser.getUsername(),60L* 1000L* 30L);
            UserInfo userInfo = new UserInfo();
            userInfo.setToken(token);
            userInfo.setUser(temp);
            return CBECReturn.build(ResultCode.SUCCESS, userInfo);
        }
        //与数据库不一致，返回登录页面
        return CBECReturn.build(ResultCode.USER_INFO_ERROR);
    }

}
